import ast
import importlib

from common.result_func import request_info_obj, return_error


# 方法扫描及执行
def calculator(request_info):
    # 字符串转为接收对象, 若不合法则返回异常信息
    request_obj = varify_request_info(request_info)
    if not isinstance(request_obj, request_info_obj):
        return request_obj
    # 获取方法的模块名, 方法名及参数
    func_base_name = request_obj.func_name[0:request_obj.func_name.index('_4_')]
    func_name = request_obj.func_name[request_obj.func_name.index('_4_') + 3:len(request_obj.func_name)]
    func_params = ast.literal_eval(str(request_obj.params))
    module = importlib.import_module("service." + func_base_name)
    func_obj = getattr(module, func_name)
    param_values = []
    for k, v in func_params.items():
        param_values.append(v)
    return func_obj(*param_values)


def varify_request_info(request_info):
    try:
        request_info_json_obj = ast.literal_eval(request_info)
        request_obj = request_info_obj()
        request_obj.__dict__ = request_info_json_obj
    except ValueError:
        return return_error('请求的数据格式错误', ValueError);
    return request_obj

# calculator('{"func_name":"method_one_4_m12", "params":{"m12_p1":"测试参数123","m12_p2":"测试参数456"}}')
